package com.sto.stoapp.activity.administrator.system;

import android.os.Bundle;
import android.provider.Settings;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.WindowManager;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;

import com.sto.stoapp.activity.R;
import com.sto.stoapp.broadcast.HomeBroadAction;
import com.sto.stoapp.widget.StoHomeActivity;

public class SystemBackLightActivity extends StoHomeActivity {

	private SeekBar seekBar;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.system_back_light);
		String broadType = getIntent().getStringExtra(
				HomeBroadAction.BROAD_TYPE);
		// 判断是管理员的系统设置还是业务内部的系统设置
		if (broadType != null && !broadType.equals("")) {
			this.setTitleBottom(R.string.back_light, broadType);
		} else {
			this.setTitleBottom(R.string.back_light,
					HomeBroadAction.ADMINISTRATOR_BROAD);
		}
		initWidget();
		initListener();
	}

	private void initListener() {
		seekBar.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(View arg0, int arg1, KeyEvent arg2) {
				setScreenLight();
				return false;
			}
		});

		seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				setScreenLight();
			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
			}

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
			}
		});
	}

	private void setScreenLight() {
		// 取得当前进度
		int tmpInt = seekBar.getProgress();

		// 当进度小于80时，设置成80，防止太黑看不见的后果。
		if (tmpInt < 30) {
			tmpInt = 30;
		}

		// 根据当前进度改变亮度
		Settings.System.putInt(getContentResolver(),
				Settings.System.SCREEN_BRIGHTNESS, tmpInt);
		tmpInt = Settings.System.getInt(getContentResolver(),
				Settings.System.SCREEN_BRIGHTNESS, -1);
		WindowManager.LayoutParams wl = getWindow().getAttributes();

		float tmpFloat = (float) tmpInt / 255;
		if (tmpFloat > 0 && tmpFloat <= 1) {
			wl.screenBrightness = tmpFloat;
		}
		getWindow().setAttributes(wl);
	}

	private void initWidget() {
		seekBar = (SeekBar) findViewById(R.id.seek_bar);
		// 进度条绑定最大亮度，255是最大亮度
		seekBar.setMax(255);
		// 取得当前亮度
		int normal = Settings.System.getInt(getContentResolver(),
				Settings.System.SCREEN_BRIGHTNESS, 255);
		// 进度条绑定当前亮度
		seekBar.setProgress(normal);

	}

}
